package com.hsource.doctorcenter.manager;

import com.alibaba.fastjson.JSONObject;
import com.hsource.doctorcenter.conf.redis.PubSubTable;
import com.hsource.doctorcenter.domain.message.MessageVO;
import com.hsource.doctorcenter.service.order.IOrderService;
import com.hsource.doctorcenter.util.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author yangYang
 * @version 1.0
 * @date 2020/10/12 15:54
 * @describe
 */
@Slf4j
@Component
public class OrderNotifyTerminalManager implements MessageListener {

    @Autowired
    private PubSubTable pubSubTable;
    @Autowired
    private StringRedisTemplate redisTemplate;

    public void addChannel(String topic) {

        pubSubTable.addComsumer(topic, this.getClass().getSimpleName());
        log.info("%s 订阅一个主题%s%n", this.getClass().getSimpleName(), topic);

    }


    @Override
    public void onMessage(Message message, @Nullable byte[] pattern) {
        IOrderService orderService = SpringUtils.getBean(IOrderService.class);
        String name = this.getClass().getSimpleName();
        String topic = new String(message.getChannel());
        String content = new String(message.getBody());
        MessageVO messageVO = JSONObject.parseObject(content, MessageVO.class);
        //如果这个取出来的不是正确的id，丢弃并记录。
        log.info("orderData=====" + content);
        Map<String, String> dataMap = (Map<String, String>) messageVO.getData();
        if (dataMap.get("return_code").equals("SUCCESS")) {
            String orderPayType = dataMap.get("orderPayType");
            if (orderPayType.equals("WECHAT")) {
                orderService.callBackOrders(dataMap.get("return_code").toUpperCase(), dataMap.get("transaction_id"), dataMap.get("out_trade_no"), orderPayType, JSONObject.toJSONString(dataMap));
            }
            if (orderPayType.equals("ALIPAY")) {
                orderService.callBackOrders(dataMap.get("return_code").toUpperCase(), dataMap.get("trade_no"), dataMap.get("out_trade_no"), orderPayType, JSONObject.toJSONString(dataMap));
            }
            redisTemplate.expire(topic + "_" + name + "_" + messageVO.getMessageId(), 1, TimeUnit.NANOSECONDS);
        }
    }
}
